package com.xiebishe.mylibrary.common.mvvm;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

/**
 * @author liujie
 * 列表数据观察者，修改回调方法区分第一次加载数据和加载更多数据
 */
public class BaseListLiveData<T> {
    public static final int STATE_LISTCONTENT = 1;//获取数据成功
    public static final int STATE_LISTEMPTY = 2;//获取数据为空
    public static final int STATE_LISTLOADING = 3;//获取数据中
    public static final int STATE_LISTERROR = 4;//获取数据失败
    public static final int STATE_LISTLOADMOREFAIL = 5;//再次获取数据失败
    public static final int STATE_NEXTLISTLOADING = 6;//再次获取数据中
    private ListChangedObserver<T> listChangedObserver;

    @IntDef({STATE_LISTERROR, STATE_LISTEMPTY, STATE_LISTLOADING, STATE_LISTCONTENT, STATE_LISTLOADMOREFAIL, STATE_NEXTLISTLOADING})
    public @interface LiveDataStatus {
    }

    public BaseListLiveData() {
    }

    public void observe(@NonNull LifecycleOwner owner, @NonNull ListChangedObserver<T> observer) {

        this.listChangedObserver = observer;
        owner.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                listChangedObserver = null;
            }
        });
    }

    public void onListIncrease(T datIncreased) {
        if (listChangedObserver != null) {
            listChangedObserver.onListIncrease(datIncreased);
        }
    }

    public void onListRefresh(T dataAll, int totalElements) {
        if (listChangedObserver != null) {
            listChangedObserver.onListRefresh(dataAll, totalElements);
        }
    }

    public void onLiveDataStatus(@LiveDataStatus int state) {
        if (listChangedObserver != null) {
            listChangedObserver.onLiveDataStatus(state);
        }
    }

    public static abstract class ListChangedObserver<T> {
        public abstract void onListIncrease(T data);

        public abstract void onListRefresh(T data, int totalElements);

        public abstract void onLiveDataStatus(@LiveDataStatus int state);

        public void onChanged(@Nullable T t) {
        }
    }
}
